package com.ys.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ys.common.constant.AuthServerConstant;
import com.ys.common.exception.BizCodeEnum;
import com.ys.common.utils.R;
import com.ys.common.vo.MemberResponseVo;
import com.ys.gulimall.auth.feign.MemberFeignService;
import com.ys.gulimall.auth.feign.ThirdPartFeignService;
import com.ys.gulimall.auth.vo.UserLoginVo;
import com.ys.gulimall.auth.vo.UserRegisterVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Description:
 * @author： yeswater
 * @create： 2024/5/14
 */

@Slf4j
@Controller
public class LoginController {
	
	@Resource
	ThirdPartFeignService thirdPartFeignService;
	
	@Resource
	StringRedisTemplate stringRedisTemplate;
	
	@Resource
	MemberFeignService memberFeignService;
	
	// Error resolving template [sms/sendcode]
	@ResponseBody
	@GetMapping("/sms/sendcode")
	public R sendCode(@RequestParam("phone") String phone) {
		// 1、接口防刷
		String prefixPhone = AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone;
		String redisCode = stringRedisTemplate.opsForValue().get(prefixPhone);
		if (!StringUtils.isEmpty(redisCode)) {
			long l = Long.parseLong(redisCode.split("_")[1]);
			if (System.currentTimeMillis() - l < 60000) {
				return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMessage());
			}
		}
		// 2、生成验证码, 设置过期时间
		//String code = UUID.randomUUID().toString().substring(0,5);
		String code = "111111";
		stringRedisTemplate.opsForValue().set(prefixPhone, code + "_" + System.currentTimeMillis(), 10, TimeUnit.MINUTES);
		//thirdPartFeignService.sendCode(phone, code);
		return R.ok();
	}
	
	@PostMapping("/register")
	public String register(@Validated UserRegisterVo vo, BindingResult result, RedirectAttributes redirectAttributes) {
		if (result.hasErrors()) {
			Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
			//model.addAttribute("errors", errors);
			redirectAttributes.addFlashAttribute("errors", errors);
			return "redirect:http://auth.gulimall.com/reg.html";
		}
		
		//校验验证码
		String code = vo.getCode();
		String val = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
		
		if (!StringUtils.isEmpty(val)) {
			if(code.equals(val.split("_")[0])) {
				//验证码通过 删除验证码 令牌机制
				stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
				//远程服务调用 将数据存入数据库 进行真正的注册
				R r = memberFeignService.register(vo);
				if (r.getCode() == 0) {
					return "redirect:http://auth.gulimall.com/login.html";
				} else {
					Map<String, String> errors = new HashMap<>();
					errors.put("msg", r.getData("msg", new TypeReference<String>(){}));
					redirectAttributes.addFlashAttribute("errors", errors);
					return "redirect:http://auth.gulimall.com/reg.html";
				}
			} else {
				Map<String, String> errors = new HashMap<>();
				errors.put("code", "验证码错误");
				redirectAttributes.addFlashAttribute("errors", errors);
				return "redirect:http://auth.gulimall.com/reg.html";
			}
		} else {
			Map<String, String> errors = new HashMap<>();
			errors.put("code", "验证码错误");
			redirectAttributes.addFlashAttribute("errors",errors);
			return "redirect:http://auth.gulimall.com/reg.html";
		}
	}
	
	public String loginPage(HttpSession session) {
		Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
		if (attribute == null) {
			return "login";
		} else {
			return "direct:http:gulimall.com";
		}
	}
	
	@PostMapping("/login")
	public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
		//远程登录
		R login = memberFeignService.login(vo);
		if (login.getCode() == 0){
			//成功
			MemberResponseVo data = login.getData("data", new TypeReference<MemberResponseVo>() {});
			log.info("登陆成功：用户信息" + JSON.toJSONString(data));
			session.setAttribute(AuthServerConstant.LOGIN_USER,data);
			return "redirect:http://gulimall.com";
		}else{
			Map<String,String> errors = new HashMap<>();
			errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
			redirectAttributes.addFlashAttribute("errors",errors);
			return "redirect:http://auth.gulimall.com/login.html";
		}
	}
	
}
